package com.xin.di.uav.applet.controller;

import com.alibaba.fastjson.JSONObject;
import com.xin.di.uav.common.exception.BusinessException;
import com.xin.di.uav.common.utils.Rs;
import com.xin.di.uav.operate.po.PlacementPoint;
import com.xin.di.uav.operate.rest.PlacementPointRest;
import com.xin.di.uav.operate.service.LoginService;
import com.xin.di.uav.utils.HttpClientUtil;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Base64;
import java.util.Map;

/**
 * @author 01430312
 */
@RestController
@RequestMapping("/home/wx/")
@Tag(name = "获取微信相关信息", description = "获取微信相关信息")
@Slf4j
public class SysWxController {
    @Autowired
    private LoginService loginService;

    @Value("${proxy-url:sfproxy.intsit.sfcloud.local}")
    private String proxyUrl;

    @Value("${is-use-proxy:false}")
    private boolean isUseProxy;

    @Autowired
    private PlacementPointRest placementPointRest;

    //方的小程序码
    @RequestMapping("/get-placement_point-wx-qrcode")
    @Parameter(name = "placementPointId", description = "投放点id")
//    @Parameter(name = "path", description = "小程序码跳转页面路径及携带参数")
    public Rs<String> createPlacementPointQRCode(
            @RequestParam String placementPointId,
            HttpServletResponse response) {
        PlacementPoint placementPoint = placementPointRest.getPlacementPointById(placementPointId);
        if (ObjectUtils.isEmpty(placementPoint)) {
            throw new BusinessException("投放点不存在");
        }
        try {
            //获取AccessToken
            String accessToken = loginService.getRescueStableToken();
            //设置响应类型
            response.setContentType("image/png");
//            https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN
            String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken;
            //组装参数
            JSONObject jsonObject = new JSONObject();
            //二维码携带参数 不超过32位 参数类型必须是字符串
//            jsonObject.put("scene", placementPointId);
            //二维码跳转页面
            StringBuilder sb = new StringBuilder();
            String pathOne = "pages/homepage/homepage?id=";
            String keyWord = "&key=fyScenicSpot";
            sb.append(pathOne).append(placementPointId).append(keyWord);
            jsonObject.put("path", sb);
//            jsonObject.put("env_version", cloudEnvVersion);
            //二维码的宽度
            jsonObject.put("width", 1280);
            //自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调
            jsonObject.put("auto_color", false);
            //是否需要透明底色， is_hyaline 为true时，生成透明底色的小程序码
            jsonObject.put("is_hyaline", false);
            //执行post 获取数据流
            byte[] result = doImgPost(url, jsonObject);
            return Rs.success(Base64.getEncoder().encodeToString(result));
        } catch (Exception e) {
            log.info("错误原因" + e);
            e.printStackTrace();
        }
        return Rs.failed();
    }

    //方的小程序码
//    @RequestMapping("/get-placement_point-wx-qrcodePeiSong")
//    @Parameter(name = "placementPointId", description = "投放点id")
////    @Parameter(name = "path", description = "小程序码跳转页面路径及携带参数")
//    public Rs<String> createPlacementPointQRCodePeiSong(
////            @RequestParam String placementPointId,
//            HttpServletResponse response) {
////        PlacementPoint placementPoint = placementPointRest.getPlacementPointById(placementPointId);
////        if (ObjectUtils.isEmpty(placementPoint)) {
////            throw new RuntimeException("投放点不存在");
////        }
//        try {
//            //获取AccessToken
//            String accessToken = loginService.getSameCityStableToken();
//            //设置响应类型
//            response.setContentType("image/png");
////            https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN
//            String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken;
//            //组装参数
//            JSONObject jsonObject = new JSONObject();
//            //二维码携带参数 不超过32位 参数类型必须是字符串
////            jsonObject.put("scene", placementPointId);
//            //二维码跳转页面
//            jsonObject.put("path", "pages/homepage/homepage");
////            jsonObject.put("env_version", cloudEnvVersion);
//
//            //二维码的宽度
//            jsonObject.put("width", 450);
//            //自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调
//            jsonObject.put("auto_color", false);
//            //是否需要透明底色， is_hyaline 为true时，生成透明底色的小程序码
//            jsonObject.put("is_hyaline", false);
//            //执行post 获取数据流
//            byte[] result = doImgPost(url, jsonObject);
//            return Rs.success(Base64.getEncoder().encodeToString(result));
//        } catch (Exception e) {
//            logger.info("错误原因"+e);
//            e.printStackTrace();
//        }
//        return Rs.failed();
//    }

    //圆的小程序码
//    @RequestMapping("/get-placement_point-wx-qrcode")
//    @Parameter(name = "placementPointId", description = "投放点id")
//    @Parameter(name = "page", description = "小程序码跳转页面")
//    public Rs<String> createPlacementPointQRCode(
//            @RequestParam(required = false) String page,
//            @RequestParam String placementPointId,
//            HttpServletResponse response) {
//        PlacementPoint placementPoint = placementPointRest.getPlacementPointById(placementPointId);
//        if (ObjectUtils.isEmpty(placementPoint)) {
//            throw new RuntimeException("投放点不存在");
//        }
//        try {
//            //获取AccessToken
//            String accessToken = loginService.getRescueStableToken();
//            //设置响应类型
//            response.setContentType("image/png");
//            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
//            //组装参数
//            JSONObject jsonObject = new JSONObject();
//            //二维码携带参数 不超过32位 参数类型必须是字符串
//            jsonObject.put("scene", placementPointId);
//            //二维码跳转页面
//            jsonObject.put("page", page);
//            jsonObject.put("env_version", cloudEnvVersion);
//
//            //二维码的宽度
//            jsonObject.put("width", 450);
//            //自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调
//            jsonObject.put("auto_color", false);
//            //是否需要透明底色， is_hyaline 为true时，生成透明底色的小程序码
//            jsonObject.put("is_hyaline", false);
//            //执行post 获取数据流
//            byte[] result = doImgPost(url, jsonObject);
//            return Rs.success(Base64.getEncoder().encodeToString(result));
//        } catch (Exception e) {
//            logger.info("错误原因"+e);
//            e.printStackTrace();
//        }
//        return Rs.failed();
//    }

    /**
     * 获取数据流
     *
     * @param url
     * @param paraMap
     * @return
     */
    public byte[] doImgPost(String url, JSONObject paraMap) {
        byte[] result = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            // 设置请求的参数
            JSONObject postData = new JSONObject();
            for (Map.Entry<String, Object> entry : paraMap.entrySet()) {
                postData.put(entry.getKey(), entry.getValue());
            }
            result = HttpClientUtil.sendPostJsonRepeatProxyForPicture(url, JSONObject.toJSONString(paraMap), proxyUrl, 80, false);

        } catch (Exception e) {
            log.info("错误原因" + e);
            e.printStackTrace();
        }
        return result;
    }
}
